package com.gd.iot.energy.util;

import cn.hutool.core.date.DateUtil;
import com.gd.iot.energy.code.ResponseCode;
import com.gd.iot.energy.consts.SystemConsts;
import com.gd.iot.energy.exception.MyException;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义字符串工具类
 */
public class CustomStrUtil {

    private static Pattern linePattern = Pattern.compile("_(\\w)");

    /**
     * 下划线转驼峰
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    private static final Pattern humpPattern = Pattern.compile("[A-Z]");

    /**
     * 驼峰转下划线
     */
    public static String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 判断是否是邮箱
     *
     * @return
     */
    public static boolean isEmail(String string) {
        if (string == null) {
            return false;
        }
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p;
        Matcher m;
        p = Pattern.compile(regEx1);
        m = p.matcher(string);
        return m.matches();
    }

    /**
     * 生成
     *
     * @param prefix
     * @return
     */
    public static String getDateNumber(final SystemConsts.Prefix prefix) {
        final String dateTime = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        return prefix.name() + dateTime;
    }

    /**
     * 字符串转2位小数BigDecimal
     *
     * @param str 字符串数字
     * @return
     */
    public static BigDecimal str2BigDecimalScala2(String str) {
        try {
            return BigDecimal.valueOf(Double.parseDouble(str))
                    .setScale(2, RoundingMode.HALF_UP);
        } catch (Exception e) {
            throw new MyException(ResponseCode.PARAMETER_ERROR);
        }
    }

    /**
     * 每隔2个字符空一格
     * @param input
     * @return
     */
    public static String formatHex(String input){
        String regex = "(.{2})";
        input = input.replaceAll(regex, "$1 ");
        return input;
    }
}
